<?php

namespace App\Dao;

use App\Exceptions\SysExceptions;
use App\Model\OrdersModel;
use App\Services\PayServices;
use Illuminate\Support\Facades\DB;

class OrdersDao extends BaseDao
{
    public static function builder_query($params = []): \Illuminate\Database\Eloquent\Builder
    {
        $query = OrdersModel::query();
        $query->when(checkIsHasField($params,'order_id'),function ($query)use ($params){
            $query->where('order_id',$params['order_id']);
        });

        $query->when(checkIsHasField($params,'user_id'),function ($query)use ($params){
            $query->where('user_id',$params['user_id']);
        });

        $query->when(checkIsHasField($params,'status'),function ($query)use ($params){
            $query->where('status',$params['status']);
        });

        $query->when(checkIsHasField($params,'pay_orders_code'),function ($query)use ($params){
            $query->where('pay_orders_code',$params['pay_orders_code']);
        });

        $query->when(checkIsHasField($params,'goods_title_like'),function ($query)use ($params){
            $query->where('order_json_data','LIKE','%'.$params['goods_title_like'].'%');
        });


        $query->when(checkIsHasField($params,'start_time'),function ($query)use ($params){
            $query->where('created_at','>=',strtotime($params['start_time']));
        });

        $query->when(checkIsHasField($params,'end_time'),function ($query)use ($params){
            $query->where('created_at','<=',strtotime($params['end_time'].' 23:59:59'));
        });



        return $query;
    }

    /**
     * @throws SysExceptions
     */
    public static function add_order(array $params)
    {
        checkForData(
            ['goods_id', 'address_id'],
            ['请选择商品', '请选择地址'],
            $params
        );

        //判断支付密码
        $user_info = UsersDao::builder_user_query([
            'user_id' => $params['user_id']
        ])->first()->toArray();

        $goodsInfo = GoodsDao::builder_query([
            'goods_id' => $params['goods_id']
        ])->first()->toArray();
        $money = bcmul($params['nums'], $goodsInfo['goods_price'], 2);

        if($params['pay_type'] == 2){
            if (is_null($user_info['pay_pass']) || empty($user_info['pay_pass'])) {
                self::error('请设置支付密码');
            }
            if (!password_verify($params['pay_pass'], $user_info['pay_pass'])) {
                self::error('支付密码不正确!');
            }
            if($money > $user_info['balance']){
                self::error('余额不足');
            }
        }
        DB::beginTransaction();
        try {
            $params['pay_orders_code'] = makeOrderNo();
            for ($i = 0; $i < $params['nums']; $i++) {
                $params['orders_code'] = makeOrderNo();
                $params['days'] = SettingsDao::get_set_value('order_days');
                $params['address_json_data'] = json_encode(AddressDao::builder_query([
                    'address_id' => $params['address_id']
                ])->first()->toArray(), JSON_UNESCAPED_UNICODE);
                $params['price'] = $goodsInfo['goods_price'];
                $params['max_recive'] = $goodsInfo['max_recive'];
                $params['order_send_max_recive'] = $goodsInfo['max_recive'];

                $params['order_json_data'] = json_encode($goodsInfo, JSON_UNESCAPED_UNICODE);
                //微信支付
                self::builder_query()->create($params);
                sleep(1);
            }

            if($params['pay_type'] == 2){
                BillsDao::moneyUpdate($params['user_id'], -($money), '消费产品扣除');
                self::noticePay($params['pay_orders_code']);
            }

            DB::commit();
            if($params['pay_type'] == 1){
                $openid = UsersDao::builder_user_login_query([
                    'user_login_id'=>$user_info['user_login_id'],
                ])->value('openid');
                return PayServices::pay([
                    'name'=>'消费商品',
                    'price'=>$money,
                    'order_code'=>$params['pay_orders_code'],
                    'openid'=>$openid,
                    'notify_url'=>route('notice_pay_goods')
                ]);
            }
        }catch (\Exception $exception){
            DB::rollBack();
            self::error($exception->getMessage());
        }
    }

    public static function noticePay($pay_order_code = '')
    {
        $pay_orders = self::builder_query([
            'pay_orders_code'=>$pay_order_code,
            'status'=>0
        ]);
        if(!$pay_orders->exists()){
            return false;
        }
        $pay_orders = $pay_orders->get()->toArray();
        foreach ($pay_orders as $value){
            $params = [];
            $params['user_id'] = $value['user_id'];
//            $goodsInfo = json_decode($value['order_json_data'],true);
            //计算个人金币
//            $be_data = self::send_my_score($goodsInfo);
            //金币最大
//            $params['order_send_score'] = $be_data;
//            //静态值
//            $params['order_send_score_recive'] = $params['order_send_score_jingtai'] = bcmul($be_data, 0.5, 2);
//            //动态值
//            $params['order_send_score_dongtai'] = bcmul($be_data, 0.5, 2);
//            //有一个地方存总金币量用于计算单价
//            CommonDao::mixScorePrice($be_data);
//            //发放奖励
//            CommonDao::mixGoodsPrice($goodsInfo['mix_goods_price']);
            $params['status'] = 1;
            //每人最大收益
//            UsersDao::builder_user_query([
//                'user_id' => $params['user_id']
//            ])->increment('max_recive', $goodsInfo['max_recive']);
//            UsersDao::builder_user_query([
//                'user_id' => $params['user_id']
//            ])->increment('max_recive_frozen', $goodsInfo['max_recive']);
//            self::builder_query([
//                'order_id'=>$value['order_id']
//            ])->update(self::filterFields($params,new OrdersModel()));
            //增加流水
            //判断是不是会员区的产品
//            self::changeVipLevel($goodsInfo, $params['user_id'], $goodsInfo['goods_price']);
        }
    }

    public static function noticePayLine($pay_order_code = '')
    {
        $pay_orders = self::builder_query([
            'pay_orders_code'=>$pay_order_code,
            'status'=>0
        ]);
        if(!$pay_orders->exists()){
            return false;
        }
        $pay_orders = $pay_orders->get()->toArray();
        DB::beginTransaction();
        try {
            foreach ($pay_orders as $value){
                $params = [];
                $params['user_id'] = $value['user_id'];
//                $goodsInfo = json_decode($value['order_json_data'],true);
//                //计算个人金币
//                $be_data = self::send_my_score($goodsInfo);
//                //金币最大
//                $params['order_send_score'] = $be_data;
//                //静态值
//                $params['order_send_score_recive'] = $params['order_send_score_jingtai'] = bcmul($be_data, 0.5, 2);
//                //动态值
//                $params['order_send_score_dongtai'] = bcmul($be_data, 0.5, 2);
//                //有一个地方存总金币量用于计算单价
//                CommonDao::mixScorePrice($be_data);
                //发放奖励
//                CommonDao::mixGoodsPrice($goodsInfo['mix_goods_price']);
                $params['status'] = 1;
                //每人最大收益
//                UsersDao::builder_user_query([
//                    'user_id' => $params['user_id']
//                ])->increment('max_recive', $goodsInfo['max_recive']);
//                UsersDao::builder_user_query([
//                    'user_id' => $params['user_id']
//                ])->increment('max_recive_frozen', $goodsInfo['max_recive']);
//                self::builder_query([
//                    'order_id'=>$value['order_id']
//                ])->update(self::filterFields($params,new OrdersModel()));
//                //增加流水
//                //判断是不是会员区的产品
//                self::changeVipLevel($goodsInfo, $params['user_id'], $goodsInfo['goods_price']);
            }
            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
        }
    }

    public static function datas(array $params): array
    {
        return self::builder_query($params)->where('status','<>',0)->orderByDesc('created_at')->get()->toArray();
    }

    public static function datas_info(array $params): array
    {
        return self::builder_query($params)->first()->toArray();
    }

    /**
     * @throws SysExceptions
     */
    public static function confirm_orders(array $params)
    {
        checkForData(
            ['orders_id',],
            ['请选择订单'],
            $params
        );
        $ordersInfo = self::builder_query([
            'order_id'=>$params['orders_id']
        ]);
        if(!$ordersInfo->exists()){
            self::error('订单不存在');
        }
        $ordersInfo = $ordersInfo->first()->toArray();
        if($ordersInfo['status'] != 2){
            self::error('订单状态不正确');
        }
        if($ordersInfo['user_id'] != $params['user_id'])
            self::error('订单持有者不正确');
        if(self::builder_query(['order_id'=>$params['orders_id']])->update([
            'status'=>3
        ]) === false){
            self::error('订单收货失败');
        }

    }

    //发放个人金币额度进行计算
    public static function send_my_score(array $goods_info = [])
    {
        //查询实时单价
        $now_price = CommonDao::real_time_price();
        if($now_price == 0){
            return 0;
        }
        //根据分红值算最大金币
        $mix_goods_price = $goods_info['mix_goods_price'];
        //分红值*全局比例
        $sys_percent = SettingsDao::get_set_value('sys_percent');
        $maxMixGoodsPrice = bcdiv(bcmul($sys_percent,$mix_goods_price,10),$now_price,10);
        //保存到订单里
        return $maxMixGoodsPrice;
    }

    public static function pageinate(array $params)
    {
        return self::builder_query($params)->where('status','<>',0)->orderByDesc('created_at')->paginate()->toArray();
    }

    public static function orders_no_page(array $params)
    {
        $list =  self::builder_query($params)->where('status','<>',0)->orderByDesc('created_at')->get()->toArray();
        foreach ($list as &$value){
            $addJsonData = json_decode($value['address_json_data'],true);
            $value['address_str'] = $addJsonData['address_name'].'-'.$addJsonData['address_phone'].'-'.$addJsonData['address_details_str'];
            $status = ['未支付','已支付','待收货','已完成'];
            $value['status_str'] = $status[$value['status']];
            $value['created_at_str'] = date('Y-m-d H:i:s',$value['created_at']);
            $pay_arr = ['未知','微信支付','余额支付'];
            $value['pay_str'] =  $pay_arr[$value['pay_type']];
            $order_json_data = json_decode($value['order_json_data'],true);
            $value['goods_name'] = $order_json_data['goods_name'];

        }
        return $list;
    }

    //升级VIP
    private static function changeVipLevel(array $goodsInfo = [],$user_id = 0,$price = 0)
    {
        $u_uinfo = UsersDao::builder_user_query([
            'user_id'=>$user_id
        ])->first()->toArray();
        //上级用户ID
        $spread_id = $u_uinfo['spread_id'];

        if($goodsInfo['send_vip'] == 1){
            if($u_uinfo['vip_index_level'] != 1){
                UsersDao::builder_user_query([
                    'user_id'=>$user_id
                ])->update([
                    'vip_index_level'=>1,
                    'activity_time'=>time()
                ]);
            }
        }
        $l_arr = [0,3,4,5,6,7,8];
        $yeJi = [0,26000,78000,260000,1300000,5200000,15600000];


        //无限极向上级叠加业绩
        while(true){
            if($spread_id == 0){
                break;
            }
            UsersDao::builder_user_query([
                'user_id'=>$spread_id
            ])->increment('all_prices',$price);

            $spread_id = UsersDao::builder_user_query([
                'user_id'=>$spread_id
            ])->value('spread_id');
        }

        $spread_id = $u_uinfo['spread_id'];
        while(true){
            if($spread_id == 0){
                break;
            }
            //查询上级用户的下级数量
            $cCount = UsersDao::builder_user_query([
                'spread_id'=>$spread_id
            ])->where('vip_index_level',1)->count();

            $u_spreadInfo = UsersDao::builder_user_query([
                'user_id'=>$spread_id
            ])->first()->toArray();
            if($u_spreadInfo['vip_level'] == 6){
                break;
            }
            if($cCount < $l_arr[$u_spreadInfo['vip_level']+1]){

                break;
            }

            //查询业绩
            //业绩活口
            $yeJiMaxBe = $yeJi[$u_spreadInfo['vip_level']+1];
            if($u_spreadInfo['all_prices'] < $yeJiMaxBe){
                break;
            }
            //获取直推的最大业绩
            $max_all_prices = self::getMaxPrices($spread_id);
            //小区业绩只和必须大于大区1/2自己的业绩减去下级最大业绩
            $Ji = $u_spreadInfo['all_prices'];
            $MaxPrij = $max_all_prices;
            $xiaoJi = bcsub($Ji,$MaxPrij,2);
            if($xiaoJi < bcmul($MaxPrij,0.5,2)){
                break;
            }



            UsersDao::builder_user_query([
                'user_id'=>$spread_id
            ])->update([
                'vip_level'=>$u_spreadInfo['vip_level']+1
            ]);
            $spread_id = UsersDao::builder_user_query([
                'user_id'=>$spread_id
            ])->value('spread_id');
        }
    }

    /**
     * @throws SysExceptions
     */
    public static function send_huo(array $params)
    {
        checkForData(['wuliu_num'],['请输入物流单号'],$params);
        $orders_query = self::builder_query(['order_id'=>$params['order_id']]);
        if(!$orders_query->exists()){
            self::error('订单不存在!');
        }
        $orders_info = $orders_query->first()->toArray();
        if($orders_info['status'] != 1){
            self::error('订单状态不正确!');
        }

        if (self::builder_query(['order_id'=>self::deleteParamId($params,'order_id')])->update(['wuliu_num'=>$params['wuliu_num'],'status'=>2]) === false){
            self::error('修改失败');
        }
    }

    //获取最大业绩
    public static function getMaxPrices($spread_id)
    {
        $price = 0;
        //获取所有下级
        $all_upers = UsersDao::builder_user_query([
            'spread_id'=>$spread_id
        ]);
        if(!$all_upers->exists()){
            return 0;
        }
        $all_upers = $all_upers->get()->toArray();
        foreach ($all_upers as $value){
            //获取自己的购买金额
            $my_pries = self::builder_query([
                'user_id'=>$value['user_id']
            ])->where('status','>',0)
                ->sum('price');
            $my_pries = bcadd($value['all_prices'],$my_pries,2);

            //如果小于
            if($price < $my_pries){
                $price = $my_pries;
            }
        }
        return  $price;
    }


}
